from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    help = "Import all folders inside the upload folder as albums"
    
    def handle_noargs(self, **options):
        from garetjax.gallery.models import Set, Collection, import_folder
        from garetjax.gallery.forms import PHOTOS_UPLOAD_PATH
        import os
        
        dirlist = os.listdir(PHOTOS_UPLOAD_PATH)
        i = 0
        for folder in dirlist:
            if folder.startswith('.'):
                continue
            i+=1
            
            set_name = folder.split(' ')
            collection_name = set_name.pop()
            set_name = ' '.join(set_name)
            collection_name = '%s-%s' % (collection_name[2:4], collection_name[7:9])
            
            collection, created = Collection.objects.get_or_create(title=collection_name)
            set = Set(title=set_name, collection=collection)
            set.save()
            
            import_folder(os.path.join(PHOTOS_UPLOAD_PATH, folder), set)
            print i, '/', len(dirlist), '>', folder, 'saved'
        
        for c in Collection.objects.all():
            c.save()
        
        for a in Set.objects.all():
            a.save()